/** @format */

import React from 'react';

// "https://wsaudiobssdlbig.kugou.com/2005182150/bYVOtpowNaFUGIU-7upiBw/1589896205/bss/extname/wsaudio/d48fdac0ed5253cca403974000da1e7d.mp3"

interface IState {
  // 自动播放
  autoplay?: boolean;
  // 循环播放
  loop?: boolean;
  // 是否静音
  muted?: boolean;
  //
  preload?: 'none' | 'metadata' | 'auto' | '';
  //
  src: string;
}

interface IProps {
  // 自动播放
  play: boolean;
  // 循环播放
  loop?: boolean;
  // 是否静音
  muted?: boolean;
  //
  preload?: 'none' | 'metadata' | 'auto' | '';
  //
  src: string;
  getAudioState: (obj: any) => void;
}

class AudioPlayer extends React.Component<IProps, IState> {
  // todo
  audio: React.RefObject<HTMLAudioElement>;
  progressTimerID = 0;
  constructor(props: IProps) {
    super(props);
    this.getPlayProgress = this.getPlayProgress.bind(this);
    this.audio = React.createRef();
  }

  UNSAFE_componentWillReceiveProps(nextProp: IProps) {
    nextProp.play ? this.play() : this.pause();
  }

  getPlayProgress() {
    //this.progressTimerID = window.setInterval(()=>{
    const duration = this.audio.current.duration;
    const currentTime = this.audio.current.currentTime;
    this.props.getAudioState({
      duration,
      currentTime,
      progress: Math.floor((currentTime / duration) * 10000) / 100,
    });
    //},2000)
  }

  play() {
    this.audio.current.play();
  }

  pause() {
    this.audio.current.pause();
  }

  render(): JSX.Element {
    return (
      <audio
        ref={this.audio}
        src={this.props.src || ''}
        loop={this.props.loop || false}
        muted={this.props.muted || false}
        preload={this.props.preload || 'metadata'}
        onTimeUpdate={this.getPlayProgress}
      />
    );
  }
}

export default AudioPlayer;
